package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author:YZN
 * @date:2022/12/21
 * @description:
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Resource
    private EmployeeMapper employeeMapper;

    @Override
    public R<Employee> login(Employee employee) {
        //1.校验参数
        if (StringUtils.isBlank(employee.getUsername())||StringUtils.isBlank(employee.getPassword())){
            return R.error("参数异常");
        }
        //2.密码md5加密
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        //3.通过用户名查询数据库员工
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeMapper.selectOne(queryWrapper);
        //4.判断员工是否存在
        if (emp == null){
            return R.error("登录失败");
        }
        //5.判断密码是否正确
        if (!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }
        //6.判断账号状态是否被禁用
        if (emp.getStatus() == 0){
            return R.error("员工已禁用");
        }

        return R.success(emp);
    }

    @Override
    public void add( Employee employee) {
        //todo 1.补全参数
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);

        //todo 2.加入数据库
        employeeMapper.insert(employee);
    }

    @Override
    public R page(Integer page, Integer pageSize, String name) {

        IPage<Employee> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(name),Employee::getName,name);
        employeeMapper.selectPage(pageInfo,wrapper);
        return R.success(pageInfo);
    }

    @Override
    public R modify(Employee employee) {
        //todo 校验参数
        if (employee == null){
            return R.error("参数异常");
        }
        //todo 根据ID修改状态
        employeeMapper.updateById(employee);
        return R.success("员工状态修改成功");
    }

    @Override
    public R findById(Long id) {
        if (id == null){
            return R.error("参数异常");
        }
        Employee employee = employeeMapper.selectById(id);
        return R.success(employee);
    }
}
